#!/usr/bin/env python
# -*- coding:utf-8 -*- #
import sys
import os
import atexit
sys.path.append(os.getcwd())
sys.path.append(os.pardir)

import threading
from probe.core.threadmanager import ThreadManager
from probe.core.cmdloader import CmdLoader
from worktype import Monitor, Alarm, Logger
from probe.watch.notify import watch
from probe.logger.logger import getlogger
from probe.conf import configure

class Probe(object):
    def __init__(self):
        self.monitor = None
        self.logger = None
        self.alarm = None
        self.threadmanager = None
        self.conf_info = configure.cmdconfig
        self.object_cmdloader = CmdLoader() #实例化对象
        self.event = threading.Event()

    def set_daemonize(self, flag, pidfile):
        """make program run as daemon"""
        if flag:
            if os.path.isfile(pidfile):
                pid = open(pidfile).read().strip()
                import commands
                if pid and commands.getoutput('ps %s |grep %s' % (pid, pid)):
                    getlogger(configure.logger_path).error("Probes has startup")
                    print("Probes has startup\n")
                    print("You can kill %s to enable probes" %  pid)
                    sys.exit(1)
                pid = os.fork()
                if pid == 0:
                    os.setsid()
                    pid = os.fork()
                    if pid == 0:
                        #os.chdir('/')
                        os.umask(022)
                        open(pidfile, 'w').write('%s' % os.getpid())
                        print 'start: pid is: %s' % os.getpid()
                    else:
                        sys.exit(0)
                else:
                    sys.exit(0)

    def run(self):
        if not configure.DEBUG:
            pidfile = 'pidfile'
            self.set_daemonize(True, pidfile)
            atexit.register(lambda:os.remove(pidfile))
        else:
            print 'debug: pid is: %s' % os.getpid()

        #watching configure file
        t = threading.Thread(None, watch, args=(self.event,))
        t.setDaemon(True)
        t.start()

        threadmanager = ThreadManager()
        self.threadmanager = threadmanager
        # self.cmdloader = CmdLoader(configure.cmdconfig)
        self.object_cmdloader.load(self.conf_info) 

        self._start_gs(configure)

        self.loop()

    def _start_gs(self, configure):
        if self.conf_info.get('monitorcfg'):
            monitorcfg_detail = self.object_cmdloader.detail('monitorcfg')
            if not self.monitor:
                self.monitor = Monitor(self.threadmanager, monitorcfg_detail)
            self.monitor.load_config(monitorcfg_detail)
            
        if self.conf_info.get('alarmcfg'):
            alarmcfg_detail = self.object_cmdloader.detail('alarmcfg')
            print "alarmcfg_detail ==",alarmcfg_detail
            if not self.alarm:
                self.alarm = Alarm(self.threadmanager, alarmcfg_detail)
            self.alarm.load_config(alarmcfg_detail)
        if self.conf_info.get('loggercfg'):
            loggercfg_detail = self.object_cmdloader.detail('loggercfg')
            if not self.logger:
                self.logger = Logger(self.threadmanager, loggercfg_detail)
            self.logger.load_config(loggercfg_detail)

    def reload_config(self):
       
        self.threadmanager.recycle_all()
        import time
        time.sleep(3)

        if self.alarm:
            
            self.alarm.reset()
        reload(configure)
        self.object_cmdloader.reload_config(configure.cmdconfig)
        self._start_gs(configure)

    def loop(self):
        """check event isSet every 5 seconds"""
        
        while True:
            self.event.wait(5)
            if self.event.isSet():
                self.reload_config()
                self.event.clear()

if __name__ == '__main__':
    probe = Probe()
    probe.run()
